import { Effect, Reducer } from 'umi';
import _ from 'lodash';
import { getThemeList } from '@/pages/SystemController/ThemeController/service';
import { getKeyRouter } from '@/utils';

interface IAllTabsType {
  path: string;
  name: string;
  url: string;

  [key: string]: any;
}

export interface IndexModelState {
  name: string;
  allTabs: IAllTabsType[];
  oaParams: Record<string, any>;
}

export interface IndexModelType {
  namespace: 'navTab';
  state: IndexModelState;
  effects: {
    getThemeList: Effect;
  };
  reducers: {
    addWindow: Reducer<IndexModelState>;
    updateWindow: Reducer<IndexModelState>;
    closeCurrentWindow: Reducer<IndexModelState>;
    closeOtherWindow: Reducer<IndexModelState>;
    closeAllState: Reducer<IndexModelState>;
  };
}

const IndexModel: IndexModelType = {
  namespace: 'navTab',

  state: {
    name: '',
    allTabs: [],
    oaParams: {},
  },

  effects: {
    *getThemeList({ payload, callback }, { call, put }): any {
      const response = yield call(getThemeList);
      callback(response);
    },
  },
  reducers: {
    addWindow(state: any, action) {
      // let tabs: IAllTabsType[] = _.cloneDeep(state.allTabs);
      // let tabs: IAllTabsType[] = [];

      let addPayload = [
        {
          ...action.payload,
          key: `${action.payload?.id}_${getKeyRouter()}_${getKeyRouter()}`,
          name: action.payload?.name,
        },
      ];

      let newTabs: any[] = state?.allTabs?.concat(addPayload);

      return {
        ...state,
        allTabs: newTabs,
      };
    },

    /*更新窗口方法*/
    updateWindow(state: any, action) {
      // let tabs = _.cloneDeep(action.payload);
      // let tabs = action.payload;
      return {
        ...state,
        // allTabs: tabs,
        allTabs: action.payload,
      };
    },

    /* 关闭当前页 */
    closeCurrentWindow(state: any, action) {
      let { activeKey } = action.payload;

      // let tabs = _.cloneDeep(state.allTabs);
      // let tabs: Array<any> = state.allTabs;
      // if (tabs && tabs?.length > 0) {
      //   tabs?.forEach((item: IAllTabsType, index: number) => {
      //     if (activeKey === item?.pathname) {
      //       tabs.splice(index, 1);
      //     }
      //   });
      // }
      let tabs = state?.allTabs?.filter((item: any) => {
        return activeKey != item?.pathname;
      });
      return {
        ...state,
        allTabs: tabs,
      };
    },

    /* 关闭其他页 */
    closeOtherWindow(state: any, action) {
      let { activeKey } = action.payload;

      // let tabs = _.cloneDeep(state.allTabs);
      // let tabs: Array<any> = state.allTabs;

      let targetTabs = state?.allTabs?.find((item: any) => item?.pathname == activeKey);

      return {
        ...state,
        allTabs: targetTabs ? [targetTabs] : state?.allTabs,
      };
    },

    /*清空所有页面*/
    closeAllState(state: any, action: any) {
      return {
        ...state,
        allTabs: [],
      };
    },

  },
};

export default IndexModel;
